package com.abc20230319.demo;


/**
 * @description urlPatterns:拦截的url地址
 * filterName:拦截器名称
 */

import lombok.extern.slf4j.Slf4j;
// import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
//import org.springframework.context.annotation.Bean;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
//import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//import java.io.PrintWriter;
import java.util.List;

@Slf4j
public class GetFilter implements Filter {

    //@Autowired //虽然报错了但是实际不影响
    UserService userService;

    /*
     * 容器加载完成调用
     * */

    //    public void init(FilterConfig filterConfig) throws ServletException {
    @Override
    public void init(FilterConfig filterConfig) {
        System.out.println("getFilter init...");
        log.info("GetFilter.init");
        /* 手动注入：https://blog.csdn.net/qq_43284469/article/details/119970391 */
        ServletContext context = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
        if (ctx != null) {
            userService = ctx.getBean(UserService.class);//你要注入的服务
        }
    }

    /*
     *  请求被拦截的时候调用
     * */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("getFilter do...");
        log.info("GetFilter.doFilter");
        String username = request.getParameter("username");
        //System.out.println(username);
        List<String> list = userService.getPermissionList(username);
        System.out.println(list);
        for (String p : list) {
            if (p.equals("改")) {
                chain.doFilter(request, response);
                System.out.println("getFilter已放行" + username);
                return;
            }
        }
//        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        res.sendError(222, "您没有权限");
        System.out.println("getFilter已拦截" + username);
//        PrintWriter writer = res.getWriter();
//        writer.write("123");
//        writer.flush();
//        writer.close();
    }

    /*
     * 容器被销毁的时候调用
     * */
    @Override
    public void destroy() {
        System.out.println("getFilter destroy...");
        log.info("GetFilter.destroy");
    }
}